package com.greateffect.littlebud.lib.base;

import android.os.Handler;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.greateffect.littlebud.lib.R;
import com.greateffect.littlebud.lib.adapter.CommonRecyclerAdapter;
import com.greateffect.littlebud.lib.imageloader.ImageLoader;
import com.greateffect.littlebud.lib.listener.DoubleClickListener;
import com.greateffect.littlebud.lib.mvp.BaseBean;
import com.greateffect.littlebud.lib.mvp.IPresenter;
import com.greateffect.littlebud.lib.provider.CustomStatusPageHelper;
import com.greateffect.littlebud.lib.recyclerview.CustomLoadMoreView;
import com.greateffect.littlebud.lib.utilcode.Utils;
import com.greateffect.littlebud.lib.utils.JListKit;
import com.greateffect.littlebud.lib.utils.JLogUtil;

import java.util.List;

/**
 * Created by ZengCS on 2019/8/13.
 * E-mail:zcs@sxw.cn
 * Add:成都市天府软件园E3-3F
 */
public abstract class BaseSingleRecyclerActivity<P extends IPresenter, T extends BaseBean> extends BaseSwipeActivityAdv<P> {
    protected ImageLoader mImageLoader;// 用于加载图片的管理类,默认使用glide
    protected CommonRecyclerAdapter<T> mAdapter;
    protected List<T> mItems = JListKit.newArrayList();
    protected BaseQuickAdapter.OnItemClickListener onItemClickListener;
    private RecyclerView mRecyclerView;

    public void setOnItemClickListener(BaseQuickAdapter.OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
        if (mAdapter != null) {
            mAdapter.setOnItemClickListener((adapter, view, position) -> {
                if (position < 0 || position >= mItems.size()) return;
                T bean = mItems.get(position);
                if (bean == null) return;
                onItemClickListener.onItemClick(adapter, view, position);
            });
        }
    }

    protected void onLoadSuccess(List<T> list) {
        JLogUtil.d(TAG, "[" + getClass().getSimpleName() + "]onLoadSuccess called with " + JSON.toJSONString(list));
        hideLoading();
        if (headLoadingView != null) {
            mAdapter.removeHeaderView(headLoadingView);
        }
        mAdapter.setEnableLoadMore(true);

        if (list == null || list.size() == 0) {
            if (mItems == null || mItems.size() == 0) {
                // 没有拿到数据时，禁用下拉功能
                mSwipeRefreshLayout.setEnabled(false);
                mAdapter.setEmptyView(notDataView);
            }
            mAdapter.loadMoreEnd();
            return;
        }

        if (currPage == 1) {
            mItems.clear();
        }
        mItems.addAll(list);

        hasMoreData = mItems.size() % Utils.PAGE_SIZE == 0;
        if (currPage == 1) {
            mAdapter.setNewData(mItems);
        } else {
            if (hasMoreData) {
                mAdapter.loadMoreComplete();
            } else {
                mAdapter.loadMoreEnd();
            }
        }
        // 数据加载成功后，页数+1
        currPage++;
    }

    /**
     * 访问接口失败
     *
     * @param msg 失败信息
     */
    protected void onLoadFailed(String msg) {
        hideLoading();
        if (TextUtils.isEmpty(msg)) {
            msg = getString(R.string.txt_load_data_error);
        }
        showToast(msg);
        if (mAdapter == null) return;

        mAdapter.setEnableLoadMore(true);
        // 如果当前是第一页，加载失败后，显示errorView
        if (currPage == 1) {
            // 加载失败后，禁用下拉功能
            mSwipeRefreshLayout.setEnabled(false);
            mAdapter.setEmptyView(errorView);
            // 更新错误信息
            CustomStatusPageHelper.updateTips(errorView, msg);
        } else {// 当前不是第一页,加载失败后,会在列表底部显示重试按钮
            mAdapter.loadMoreFail();
        }
    }

    /**
     * 绑定列表适配器
     *
     * @param layoutId      元素布局id
     * @param mRecyclerView RecyclerView
     * @param layoutManager 布局管理器
     */
    protected void bindAdapter(int layoutId, RecyclerView mRecyclerView, RecyclerView.LayoutManager layoutManager) {
        this.mRecyclerView = mRecyclerView;
        mAdapter = new CommonRecyclerAdapter<T>(layoutId, mItems) {
            @Override
            protected void convert(BaseViewHolder helper, T item) {
                try {
                    BaseSingleRecyclerActivity.this.convert(helper, item);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setAdapter(mAdapter);

        // 设置加载更多能力
        mAdapter.setLoadMoreView(new CustomLoadMoreView());
        mAdapter.setEnableLoadMore(true);
        mAdapter.setOnLoadMoreListener(this::getDataFromNet, mRecyclerView);
        // 默认第一次加载会进入回调，如果不需要可以配置：
        mAdapter.disableLoadMoreIfNotFullPage();

        if (layoutManager instanceof GridLayoutManager) {
            // 这行代码可以让Header和Footer独占一行
            mRecyclerView.swapAdapter(mAdapter, true);
        }

        // 设置Actionbar双击滚动列表至顶部
        View topContainer = findViewById(R.id.id_container_toolbar);
        if (topContainer != null) {
            topContainer.setOnClickListener(new DoubleClickListener() {
                @Override
                public void onDoubleClick(View v) {
                    // 返回顶部
                    mRecyclerView.scrollToPosition(0);
                }
            });
        }
    }

    protected abstract void convert(BaseViewHolder helper, T item);

    private View headLoadingView;

    @Override
    public void onRefresh() {
        mAdapter.setEnableLoadMore(false);// 这里的作用是防止下拉刷新的时候还可以上拉加载
        if (JListKit.isEmpty(mItems))
            mAdapter.setEmptyView(mLoadingView);
        else {
            headLoadingView = LayoutInflater.from(this).inflate(R.layout.custom_status_refresh, null, false);
            mAdapter.addHeaderView(headLoadingView);
            new Handler().postDelayed(() -> mRecyclerView.smoothScrollToPosition(0), 20);
        }
        currPage = 1;
        getDataFromNet();
    }
}
